package com.lcxw.hxzbapi.controller.paycontroller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.entity.pojo.VipBuyDetail;
import com.lcxw.hxzbapi.entity.requestBean.GetVipBuyOrderInfoReqAlipay;
import com.lcxw.hxzbapi.service.VipBuyDetailService;
import com.lcxw.hxzbapi.tencentim.common.ImCommand;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lcxw.hxzbapi.entity.pojo.YwpdChargeDetail;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.YwpdChargeDetailService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.AlipayUtil;
import com.lcxw.hxzbcommon.common.StringUtil;

/**
 * 支付宝支付的相关业务实现
 *
 * @author Administrator
 */
@Slf4j
@Component
public class AlipayRealization {

    @Resource
    YwpdChargeDetailService ywpdChargeDetailService;

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    VipBuyDetailService vipBuyDetailService;

    private AlipayUtil alipayUtil = new AlipayUtil();

    @Autowired
    private TencentImRealization tencentImRealization;


    /**
     * 生成支付宝交易订单信息
     *
     * @param orderInfoParams 创建交易订单信息
     * @return Response
     */
    Response generateOrderInfo(JSONObject orderInfoParams) {

        String userId = orderInfoParams.getString("userId");
        String body = orderInfoParams.getString("body");
        String subject = orderInfoParams.getString("subject");
        String totalAmount = orderInfoParams.getString("totalAmount");
        String productCode = orderInfoParams.getString("productCode");

        int ratio = Integer.parseInt(orderInfoParams.getString("ratio"));
        int coin = Integer.parseInt(orderInfoParams.getString("coin"));
        float rmb = Float.parseFloat(totalAmount);

        //计算虚拟货币的兑换是否正确，不正确则返回计算错误
        if ((float) coin != rmb * ratio) {
            return Response.wrongParam(log, "coin miscount");
        }

        //这里生成唯一的订单id
        String outTradeNo = StringUtil.getOrderIdByUUId(1);

        //生成订单信息
        String orderInfo = alipayUtil
            .createOrderInfo(body, subject, outTradeNo, totalAmount, productCode);

        if (null == orderInfo) {
            return Response
                .common(log, "创建交易信息失败", ErrorCode.DB_OPERATE_FAIL, "create orderInfo failed",
                    null);
        }

        //开始生成一条充值记录，插入到数据库中
        YwpdChargeDetail ywpdChargedetail = new YwpdChargeDetail();
        ywpdChargedetail.setUserId(Long.parseLong(userId));
        ywpdChargedetail.setOrderNo(outTradeNo);//我们的orderNo对应支付宝的outTradeNo
        ywpdChargedetail.setChargeMode("支付宝");
        ywpdChargedetail.setRmb(Float.valueOf(totalAmount));
        ywpdChargedetail.setCoin(coin);
        ywpdChargedetail.setContent(subject);
        ywpdChargedetail.setStatus("创建交易");
        ywpdChargedetail.setProxyUId(null);
        ywpdChargedetail.setDealId(null);
        ywpdChargeDetailService.addChargeDetail(ywpdChargedetail);

        log.info("用户申请交易，创建交易记录：{}", ywpdChargedetail.toString());

        //这里是方法返回值
        JSONObject data = new JSONObject();
        data.put("orderNo", outTradeNo);
        data.put("orderInfo", orderInfo);

        return Response.ok(data);


    }

    /**
     * 对支付宝的异步通知消息进行处理，主要是对之前的支付记录设置状态，并存入交易双方账号信息等。
     */
    void completePayment(HttpServletRequest request, HttpServletResponse response) {

        //支付宝验签，并且获取支付结果信息
        JSONObject jsonObject = alipayUtil.dealAlipayNotify(request, response);

        if (null == jsonObject) {
            return;
        }
        String orderNo = jsonObject.getString("out_trade_no");
        String thirdOrderNo = jsonObject.getString("trade_no");
        String chargeTime = jsonObject.getString("gmt_payment");
        String thirdBuyerAccount = jsonObject.getString("buyer_id");
        String thirdSellerAccount = jsonObject.getString("seller_id");
        String thirdBuyerEmail = jsonObject.getString("buyer_logon_id");
        String thirdSellerEmail = jsonObject.getString("seller_email");
        String status = jsonObject.getString("trade_status");

        if ("WAIT_BUYER_PAY".equals(status)) {
            status = "等待交易";
        } else if ("TRADE_CLOSED".equals(status)) {
            status = "交易关闭";
        } else if ("TRADE_SUCCESS".equals(status)) {
            status = "交易成功";
        } else if ("TRADE_FINISHED".equals(status)) {
            status = "交易成功";
        }

        YwpdChargeDetail ywpdChargedetail = ywpdChargeDetailService.selectByOrderNo(orderNo);
        ywpdChargedetail.setThirdOrderNo(thirdOrderNo);
        ywpdChargedetail.setChargeTime(chargeTime);
        ywpdChargedetail.setThirdBuyerAccount(thirdBuyerAccount);
        ywpdChargedetail.setThirdSellerAccount(thirdSellerAccount);
        ywpdChargedetail.setThirdBuyerEmail(thirdBuyerEmail);
        ywpdChargedetail.setThirdSellerEmail(thirdSellerEmail);
        ywpdChargedetail.setStatus(status);

        ywpdChargeDetailService.updateStatusByOrderNo(ywpdChargedetail);
        log.info("交易完成，交易信息：{}", ywpdChargedetail.toString());
        if(null!=ywpdChargedetail&&!ywpdChargedetail.getContent().contains("VIP")){
            Response msg = new Response();
            msg.setCode(ImCommand.RECHARGE_NOTICE);
            msg.setDesc("Hi,你已成功充值"+ywpdChargedetail.getCoin()+"幸运币,可以用来购买会员和礼物。");
            tencentImRealization.sendmsg(tencentImRealization.generateUserBody(JSON.toJSONString(msg),ywpdChargedetail.getUserId()+""));
        }
        //完成支付后，将用户充进的虚拟货币添加到用户数据中
        ywpdMemberService
            .updateCoinByUserId(ywpdChargedetail.getCoin(), ywpdChargedetail.getUserId());

        if (status.equals("交易成功")) {
            vipBuyDetailService.checkVipBuyDetail(orderNo);
        }

    }

    /**
     * 处理支付宝充值结果
     *
     * @param requestParams 充值结果
     * @return Response
     */
    Response dealPayResult(JSONObject requestParams) {
        String orderNo = requestParams.getString("orderNo");
        String status = requestParams.getString("status");

        if ("交易未完成".equals(status)) {
            ywpdChargeDetailService.deleteByOrderNo(orderNo);
            log.info("交易未完成，用户取消交易，交易订单号:{}", orderNo);
            return Response.ok();
        }

        //从数据库中获取该条充值记录，并设置结果状态
        YwpdChargeDetail ywpdChargedetail = ywpdChargeDetailService.selectByOrderNo(orderNo);
        ywpdChargedetail.setStatus(status);

        //更新充值结果，并记录到日志
        ywpdChargeDetailService.updateStatusByOrderNo(ywpdChargedetail);
        log.info("用户{}充值结果为：{},充值人民币：{},兑换虚拟货币：{},", ywpdChargedetail.getUserId(), status,
            ywpdChargedetail.getRmb(), ywpdChargedetail.getCoin());

        return Response.ok();
    }

    Response getVipBuyOrderInfo(GetVipBuyOrderInfoReqAlipay getVipBuyOrderInfoReqAlipay) {

        String vipType = getVipBuyOrderInfoReqAlipay.getVipType();
        if (!vipType.equals("year") && !vipType.equals("month")) {
            return Response.error(ErrorCode.INVALID_PARAM, "vipType只能是year或者month");
        }

        String body = getVipBuyOrderInfoReqAlipay.getBody();
        String subject = getVipBuyOrderInfoReqAlipay.getSubject();
        String totalAmount = getVipBuyOrderInfoReqAlipay.getTotalAmount();
        String productCode = getVipBuyOrderInfoReqAlipay.getProductCode();
        long userId = Long.parseLong(getVipBuyOrderInfoReqAlipay.getUserId());

        //这里生成唯一的订单id
        String outTradeNo = StringUtil.getOrderIdByUUId(1);
        //生成订单信息
        String orderInfo = alipayUtil
            .createOrderInfo(body, subject, outTradeNo, totalAmount, productCode);

        if (null == orderInfo) {
            return Response
                .common(log, "创建交易信息失败", ErrorCode.DB_OPERATE_FAIL, "create orderInfo failed",
                    null);
        }

        //开始生成一条充值记录，插入到数据库中
        YwpdChargeDetail ywpdChargedetail = new YwpdChargeDetail();
        ywpdChargedetail.setUserId(userId);
        ywpdChargedetail.setOrderNo(outTradeNo);//我们的orderNo对应支付宝的outTradeNo
        ywpdChargedetail.setChargeMode("支付宝");
        ywpdChargedetail.setRmb(Float.valueOf(totalAmount));
        ywpdChargedetail.setCoin(0);
        ywpdChargedetail.setContent(subject);
        ywpdChargedetail.setStatus("创建交易");
        ywpdChargedetail.setProxyUId(null);
        ywpdChargedetail.setDealId(null);
        ywpdChargeDetailService.addChargeDetail(ywpdChargedetail);

        log.info("用户申请交易，创建交易记录：{}", ywpdChargedetail.toString());

        //vip的购买记录，插入到数据库
        VipBuyDetail vipBuyDetail = new VipBuyDetail();
        vipBuyDetail.setOrderNo(outTradeNo);
        vipBuyDetail.setUserId(userId);
        vipBuyDetail.setVipType(vipType);
        vipBuyDetail.setAddTime(StringUtil.getDateTime());
        vipBuyDetail.setStatus("0");
        vipBuyDetailService.save(vipBuyDetail);

        //这里是方法返回值
        JSONObject data = new JSONObject();
        data.put("orderNo", outTradeNo);
        data.put("orderInfo", orderInfo);

        return Response.ok(data);
    }
}